if ( !exists("app_root") )
    {
    stop("Need to have app_root defined to source this template.");
    };

source( paste( app_root, "cgi-lib/R/ep.io.R", sep = "/" ) );

require( affy, keep.source = FALSE );
require( gcrma, keep.source = FALSE );
require( vsn, keep.source = FALSE );

ep.normalization.gcrma = function( src, postnormpng, tgt )
    {
    load(src);
    O = gcrma(affydata);
    ep.finishnormalization( O, postnormpng, tgt, "GCRMA" );
    return("OK");
    };

ep.normalization.rma = function( src, postnormpng, tgt )
    {
    load(src);
    O = rma(affydata);
    ep.finishnormalization( O, postnormpng, tgt, "RMA" );
    return("OK");
    };

ep.normalization.vsnaffy = function( src, postnormpng, tgt )
    {
    load(src);
    O = expresso( affydata, bg.correct = FALSE, normalize.method = "vsn", pmcorrect.method = "pmonly", summary.method = "medianpolish" );
    ep.finishnormalization( O, postnormpng, tgt, "vsn" );
    return("OK");
    };

ep.normalization.vsn = function( src, postnormpng, tgt )
    {
    M = ep.readBin(src);
    O = vsn(M);
    ep.finishnormalization( O, postnormpng, tgt, "vsn", affy = FALSE );
    return ("OK");
    };

ep.normalization.liwong = function( src, postnormpng, tgt )
    {
    load(src);
    O = expresso( affydata, bg.correct = FALSE, normalize.method = "invariantset", pmcorrect.method = "pmonly", summary.method = "liwong" );
    ep.finishnormalization( O, postnormpng, tgt, "liwong" );
    return("OK");
    };

ep.finishnormalization = function( O, postnormpng, tgt, method, affy = TRUE )
    {
    if ( affy )
        {
        D = exprs(O);
        color = rainbow(ncol(D));

        png( filename = postnormpng, width = 500, height = 350, pointsize = 12 );
        par( mar= c(2.0, 2.0, 0.2, 0.2), mgp = c( 1, 0.1, 0 ), tcl = -0.25, cex.axis = 0.7 );
        boxplot( data.frame(D), col = color[1:ncol(D)], names = FALSE, ylim = c( 3, 16 ), xlab = "sample", ylab = "PM log intensities" );
        dev.off();
        }
    else
        {
        png( filename = postnormpng, width = 500, height = 350, pointsize = 12 );
        par( mar= c(2.0, 2.0, 0.2, 0.2), mgp = c( 1, 0.1, 0 ), tcl = -0.25, cex.axis = 0.7 );
        meanSdPlot(O);
        dev.off();
        }

    ep.writeBin( exprs(O), tgt );
    };
